package tech.lingrui.mnpanonymousservice.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tech.lingrui.mnpanonymousservice.model.RequestMessage;
import tech.lingrui.mnpanonymousservice.model.ResponseMessage;
import tech.lingrui.mnpanonymousservice.util.JsonUtils;

import java.security.Principal;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 测试web socket
 *
 * @author lqs2
 * @date 2018/11/25, Sun
 */
@Controller
@Slf4j
public class TestController {

    /**
     * 收到消息记数
     */
    private static AtomicInteger count = new AtomicInteger(0);


    @Autowired
    private SimpMessagingTemplate template;

    @RequestMapping("/")
    public String longChat() {
        return "index";
    }


    @RequestMapping("/websocket")
    public String login() {
        return "index";
    }


    /**
     * 返回json格式响应
     * MessageMapping 指定要接收消息的地址，类似@RequestMapping。除了注解到方法上，也可以注解到类上
     * SendTo 消息将被发送到与传入消息相同的目的地
     * 消息的返回值是通过{@link org.springframework.messaging.converter.MessageConverter}进行转换
     *
     * @param requestMessage 接收到的消息
     * @return json str
     */


    @MessageMapping("/welcome")
    @SendTo("/topic/say")
    @ResponseBody
    public String broadcast(RequestMessage requestMessage) throws JsonProcessingException {
        ResponseMessage responseMessage = new ResponseMessage();

        responseMessage.setContent("welcome," + requestMessage.getContent() + " !");
        return JsonUtils.convertToJsonStr(responseMessage);
    }

    @MessageMapping("/chat")
    //在springmvc中,可以直接在参数中获得principal,pinciple中包含当前用户信息
    public void handleChat(Principal principal, String msg){
        if ("james".equals(principal.getName())) {//硬编码,对用户姓名进行判断
            //向用户发送消息,第一个参数:接收消息的用户,第二个参数:浏览器订阅地址,第三个参数:消息
            template.convertAndSendToUser("curry",
                    "/queue/notifications", principal.getName() + "-send: " + msg);
        } else {
            template.convertAndSendToUser("james",
                    "/queue/notifications", principal.getName() + "-send: " + msg);
        }
    }



}
